<template>
  <n-grid cols="2 s:2 m:2 l:3 xl:3 2xl:3" responsive="screen">
    <n-grid-item>
      <n-form :label-width="80" :model="formValue" :rules="rules" ref="formRef">
        <n-form-item label="昵称" path="name">
          <n-input v-model:value="formValue.username" placeholder="请输入昵称"/>
        </n-form-item>

        <n-form-item label="联系电话" path="mobile">
          <n-input placeholder="请输入联系电话" v-model:value="formValue.phone" disabled/>
        </n-form-item>
        <n-form-item label="邮箱" path="email">
          <n-input placeholder="请输入邮箱" v-model:value="formValue.email"/>
        </n-form-item>
        <n-form-item label="描述" path="desc">
          <n-input v-model:value="formValue.desc" type="textarea" placeholder="请输入描述"/>
        </n-form-item>
        <n-form-item label="头像:" path="img">
          <BasicUpload
            :action="`/api/system/oss/upload`"
            :headers="uploadHeaders"
            name="files"
            :width="200"
            :height="200"
            :maxNumber=1
            @uploadChange="uploadChange"
            v-model:value="iconList"
          />
        </n-form-item>
        <div>
          <n-space>
            <n-button type="primary" @click="formSubmit">更新基本信息</n-button>
          </n-space>
        </div>
      </n-form>
    </n-grid-item>
  </n-grid>
</template>

<script lang="ts" setup>
  import {reactive, ref, onMounted, unref} from 'vue';
  import {useMessage} from 'naive-ui';
  import {useUserStore} from "@/store/modules/user";
  import {updateSystemUser} from "@/api/system/user";

  const rules = {
    userName: {
      required: true,
      message: '请输入昵称',
      trigger: 'blur',
    },
  };

  const iconList = ref([]);
  const formRef: any = ref(null);
  const message = useMessage();
  const userStore = useUserStore();
  const uploadHeaders = {
    Authorization: userStore.getToken
  };

  const formValue = ref({
    email: "",
    iconUrl: "",
    chanList: "",
    createTime: "",
    desc: "",
    firstPsIds: "",
    id: 0,
    password: "",
    phone: "",
    roleType: "",
    secondPsIds: "",
    status: "",
    updateTime: "",
    username: "",
  });


  function formSubmit() {
    formRef.value.validate(async (errors) => {
      if (!errors) {
        if (unref(iconList) && unref(iconList).length > 0) {
          unref(formValue).iconUrl = unref(iconList)[0]
        }
        console.log(formValue);
        await updateSystemUser(unref(formValue));
        message.success('修改成功，下次登陆生效');
      } else {
        message.error('验证失败，请填写完整信息');
      }
    });
  }

  onMounted(() => {
      iconList.value = [];
      formValue.value = userStore.getUser;
      iconList.value.push(unref(formValue).iconUrl)
    }
  );

  function uploadChange(files: any[]) {
    console.log(files);
    iconList.value = unref(files);
  }
</script>
